
package tolls;

import avenue.MyWindowEvent;
import javax.persistence.NonUniqueResultException;
import javax.persistence.Query;
import java.awt.event.WindowListener;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import model.ProgramRate;
import model.Vehicle;
import javax.swing.JFrame;
import model.Collection;
import model.DBManager;
import avenue.Session;
import java.awt.event.WindowEvent;



public class CollectTollForm extends javax.swing.JFrame {

    public CollectTollForm() {
        em = DBManager.em;
        if ( !em.getTransaction().isActive()){
            em.getTransaction().begin();
        }
        String dateFormat = "HH:mm:ss";
        df = new SimpleDateFormat(dateFormat);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        vehicle1 = new model.Vehicle();
        programRate1 = new model.ProgramRate();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jSeparator2 = new javax.swing.JSeparator();
        jButton5 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jSeparator3 = new javax.swing.JSeparator();
        jButton6 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jTextField6 = new javax.swing.JTextField();
        jSeparator4 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ΔΙΕΛΕΥΣΗ ΟΧΗΜΑΤΟΣ");

        jButton1.setBackground(new java.awt.Color(0, 153, 153));
        jButton1.setText("ΔΙΕΛΕΥΣΗ");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel2.setText("Αρ. Κάρτας: ");

        jLabel1.setText("Αρ. Κυκλοφορίας: ");

        jLabel3.setText("Υπόλοιπο Κάρτας: ");

        jButton5.setText("Καθαρισμός Μηνύματος");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton3.setBackground(new java.awt.Color(0, 153, 153));
        jButton3.setText("ΠΛΗΡΩΜΗ");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/cancel.gif"))); // NOI18N
        jButton4.setText("ΆΚΥΡΟ");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton6.setBackground(new java.awt.Color(0, 204, 204));
        jButton6.setText("Αναζήτηση ");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        jLabel4.setText("Τρέχον μήνας - Διελεύσεις:");

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel5.setText("Μύνημα Συστήματος:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addComponent(jLabel3)
                            .addComponent(jButton1)
                            .addComponent(jLabel5))
                        .addGap(0, 607, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(6, 6, 6)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSeparator2)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(87, 87, 87)
                                .addComponent(jButton3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jButton4)
                                .addGap(31, 31, 31))
                            .addComponent(jSeparator4)
                            .addComponent(jSeparator3, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(269, 269, 269)
                                        .addComponent(jButton6))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(92, 92, 92)
                                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(76, 76, 76)
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(106, 106, 106)
                                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 703, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 356, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton5)
                            .addGap(308, 308, 308)))
                    .addGap(6, 6, 6)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3)
                .addGap(65, 65, 65)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 91, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(23, 23, 23)
                    .addComponent(jButton6)
                    .addGap(29, 29, 29)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jSeparator3, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButton5)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jSeparator4, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButton3)
                        .addComponent(jButton4))
                    .addContainerGap()))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
           jTextArea1.setText("");
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
   
        pass = false;
        pay = false;
        fPass = false;
        c = Calendar.getInstance();
        
        
        if (jTextField2.getText().equals("")) {
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Κενός αριθμός κυκλοφορίας.\n");
            return;
        } else if (jTextField1.getText().equals("")) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Κενός αριθμός κάρτας.\n");
            return;
        }
        
        Integer cardId;
        String regNumber = jTextField2.getText();
        try { 
            cardId = Integer.parseInt(jTextField1.getText());
        } catch(NumberFormatException ex) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Μη έγκυρος αριθμός κάρτας.\n");
            return;
        }
        
    
        Query vQuery = em.createQuery("select v from Vehicle v where "
                + "v.regNumber = :regNumber and v.cardId.id = :cardId");
        
        vQuery.setParameter("regNumber", regNumber);
        vQuery.setParameter("cardId", cardId);
        
        try { 
            
            vehicle1 = (Vehicle) vQuery.getSingleResult();
            jTextField4.setText(vehicle1.getCardId().getBalance().toString());
        } catch(NoResultException ex) { 
            
           
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Ο συνδυασμός οχήματος/κάρτας δεν βρέθηκε.\n");
            return;
        } catch(NonUniqueResultException ex) { 
            
            jTextArea1.append("(" + df.format(c.getTime()) 
                        + "): Δεν επιστράφηκε μόνο ένα αποτέλεσμα!\n");
            return;
        }
        
  
        Query prRateQuery = em.createQuery("select pr from ProgramRate pr where "
                + "pr.stationId = :stationId and pr.categoryId = :categoryId and "
                + "pr.programId = :programId");
        prRateQuery.setParameter("stationId", Session.loginUser.getStationId());
        prRateQuery.setParameter("categoryId", vehicle1.getCategoryId());
        prRateQuery.setParameter("programId", vehicle1.getCardId().getProgramId());
        
        try { 
           
            programRate1 = (ProgramRate) prRateQuery.getSingleResult();
        } catch(Exception ex) { 
        
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Δεν υπάρχει ο πίνακας των χρεώσεων του σταθμού!\n");
            return;
        }
        
        Query numPassQuery = em.createQuery("select c from Collection c where "
                + "c.cardId = :cardId");
        numPassQuery.setParameter("cardId", vehicle1.getCardId());
        
        List<Collection> collections;
        try { 
             collections = numPassQuery.getResultList();
        } catch(Exception ex) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Δεν υπάρχει ο αριθμός διελεύσεων του οχήματος!\n");
            return;
        }
        
        Integer numPass = 0;
        Calendar rn = Calendar.getInstance();
        Calendar r = Calendar.getInstance();
        for (Collection c : collections) { 
             r.setTime(c.getPassTimestamp());
             if (rn.get(Calendar.MONTH) == r.get(Calendar.MONTH))
                 numPass++;
        }
        
        jTextField6.setText(numPass.toString());
        
        pay = true;
        
        if (vehicle1.getCardId().getProgramId().getPaymentLimit() < numPass) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Μέγιστος αριθμός διελεύσεων "
                        + "του προγράμματος της κάρτας (" 
                        + vehicle1.getCardId().getProgramId().getPaymentLimit().intValue() + 
                        "). Διέλευση χωρίς χρέωση.\n");

            fPass = true;
            pass = true;
        } else if (vehicle1.getCardId().getBalance().doubleValue() >= 
            programRate1.getRate().doubleValue()) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Επαρκές υπόλοιπο διέλευσης (" 
                        + programRate1.getRate().doubleValue() + " €). "
                        + "Ενεργοποίηση επιλογών.\n");
            pass = true;
        } else { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Μη επαρκής υπόλοιπο διέλευσης!\n");
            pass = false;
        }
        
        if (vehicle1.getCardId().getBalance().doubleValue()<5.00) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): H κάρτα έχει υπόλοιπο κάτω από 5 € "
                        + "Επιθυμητή η φόρτιση της κάρτας του πελάτη;\n");
        }
                        
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        c = Calendar.getInstance();
        
        if (!pay) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Η επιλογή πληρωμής είναι ανενεργή. "
                      + "Αναζήτηση οχήματος για πληρωμή.\n");
            return;
        }

        PaymentForm pForm = new PaymentForm();
        pForm.setVisible(true);
        thisFrame=this;
        thisFrame.setEnabled(false);
       
        pForm.addWindowListener(new WindowListener() {
            public void windowClosed(WindowEvent arg0) {
                System.out.println("Σφάλμα! Το παράθυρο θα κλείσει!");
                if (((MyWindowEvent)arg0).exitAndSave){
                    jTextField4.setText(vehicle1.getCardId().getBalance().toString());
                    thisFrame.setEnabled(true);
                    pass = true;
                }
                else{
                    thisFrame.setEnabled(true);
                }
            }
            public void windowActivated(WindowEvent arg0) {
                System.out.println("Το παράθυρο είναι ενεργό");
            }
            public void windowClosing(WindowEvent arg0) {
                System.out.println("Window Closing");
            }
            public void windowDeactivated(WindowEvent arg0) {
                System.out.println("Window Deactivated");
            }
            public void windowDeiconified(WindowEvent arg0) {
                System.out.println("Window Deiconified");
            }
            public void windowIconified(WindowEvent arg0) {
                System.out.println("Window Iconified");
            }
            public void windowOpened(WindowEvent arg0) {
                System.out.println("Window Opened");
            }
        });        
        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        c = Calendar.getInstance();
        
        if (!pass) { 
            jTextArea1.append("(" + df.format(c.getTime()) + 
                        "): Η επιλογή διέλευσης είναι ανενεργή. "
                      + "Αναζήτηση οχήματος για διέλευση.\n");
            return;
        }
        
        double tollCollected;
        if (fPass) { 
            tollCollected = 0;
        } else { 
            tollCollected = programRate1.getRate().doubleValue();
            double oldBalance = vehicle1.getCardId().getBalance();
            vehicle1.getCardId().setBalance(oldBalance - tollCollected);
        }
        
        Collection col = new Collection();
        col.setStationId(Session.loginUser.getStationId());
        col.setCardId(vehicle1.getCardId());
        col.setPassTimestamp(new Date());
        col.setTollCollected(new BigDecimal(tollCollected));
        em.persist(col);
        
        em.getTransaction().commit();
        em.getTransaction().begin();
        
        dispose();
        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        em.getTransaction().rollback();
        em.getTransaction().begin();
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CollectTollForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CollectTollForm().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField6;
    private model.ProgramRate programRate1;
    private model.Vehicle vehicle1;
    // End of variables declaration//GEN-END:variables
  EntityManager em;
    JFrame thisFrame;
    private Calendar c;
    private SimpleDateFormat df;
    private boolean pass = false;
    private boolean pay = false;
    private boolean fPass = false;
}
